using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;

namespace LP
{
    public abstract class UIComposite : UIBase
    {
        private Dictionary<Type, UISub> subPanels = new Dictionary<Type, UISub>();

        public UIComposite(int id, string uiPath, bool isCache, Transform rootTrans, EUIType uIType) : base(id, uiPath, isCache, rootTrans, uIType)
        {
        }

        public override void OnInit()
        {
            base.OnInit();
            RegSubPanels();
            foreach (var item in subPanels.Values)
            {
                item.OnInit();
            }
        }

        public abstract void RegSubPanels();

        public override void OnInitFinish()
        {
            base.OnInitFinish();
            foreach (var item in subPanels.Values)
            {
                item.OnInitFinish();
            }
        }

        public override void OnUpdate(float delta)
        {
            base.OnUpdate(delta);
            foreach (var item in subPanels.Values)
            {
                base.OnUpdate(delta);
                if (item.IsUpdate)
                {
                    item.OnUpdate(delta);
                }
            }
        }

        public override void OnShowBefore()
        {
            base.OnShowBefore();
            foreach (var item in subPanels.Values)
            {
                item.OnShowBefore();
            }
        }

        public override void OnShow(ITuple tuple = null)
        {
            base.OnShow(tuple);
            foreach (var item in subPanels.Values)
            {
                item.OnShow(tuple);
            }
        }

        public override void OnHideBefore()
        {
            base.OnHideBefore();
            foreach (var item in subPanels.Values)
            {
                item.OnHideBefore();
            }
        }

        public override void OnHide(ITuple tuple = null)
        {
            base.OnHide(tuple);
            foreach (var item in subPanels.Values)
            {
                item.OnHide(tuple);
            }
        }

        public override void OnDestroy()
        {
            foreach (var item in subPanels.Values)
            {
                item.OnDestroy();
            }
            base.OnDestroy();
        }

        protected void RegSubPanel<T>() where T : UISub
        {
            Type type = typeof(T);
            if (!subPanels.ContainsKey(type))
            {
                UISub uISub = Activator.CreateInstance(type, RootTrans, TokenSource) as UISub;
                subPanels.Add(type, uISub);
            }
        }

        protected T RetriveSubPanel<T>() where T : UISub
        {
            subPanels.TryGetValue(typeof(T), out var ret);
            return ret != null ? ret as T : null;
        }
    }
}